package cn.conac.rc.gateway.modules.share.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.DateUtils;
import cn.conac.rc.gateway.base.ResultPojo;
import cn.conac.rc.gateway.common.entity.AreaEntity;
import cn.conac.rc.gateway.common.service.AreaService;
import cn.conac.rc.gateway.common.vo.AreaTreeVo;
import cn.conac.rc.gateway.common.vo.AreaVo;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.modules.ofs.vo.OrganizationVo;
import cn.conac.rc.gateway.modules.share.contsant.Contsants;
import cn.conac.rc.gateway.modules.share.service.ShareAreaService;
import cn.conac.rc.gateway.modules.share.vo.SharedAreaVo;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value={"share/"} )
@Api(tags = "地区共享信息", description = "共享地区")
public class ShareAreaController {
		
		@Autowired
		AreaService  areaService;
		
		@Autowired
		ShareAreaService  sharedAreaService;
		
		@Autowired
		OrganizationService orgService;
		
		@ApiOperation(value = "获取可共享的地区信息", httpMethod = "GET", response = OrganizationVo.class, notes = "获取可共享的地区信息")
		@RequestMapping(value = "areas", method = RequestMethod.GET)
		public Object findShareAreas(HttpServletRequest request, HttpServletResponse response) {
			ResultPojo result = new ResultPojo();
			// 获得用户所在地区的lvl
			String currAreaLvl = UserUtils.getCurrentUser().getAreaLvl();
			String currAreaCode = UserUtils.getCurrentUser().getAreaCode();
			//TODO 测试用
			// 县级别测试
			currAreaLvl = "3";
			currAreaCode = "162401136";
			//市级别测试
//			currAreaLvl = "2";
//			currAreaCode = "162400000";
			
			AreaVo areaVoPara = new AreaVo();
			areaVoPara.setIsPublic(Contsants.AREA_PUBLIC);
			areaVoPara.setNoSelfFlag(1);
			areaVoPara.setCode(currAreaCode);
			JSONObject jsonSharedAreaObj = null;
			SharedAreaVo sharedAreaVoTmp = null;
			JSONObject shareAreaInfo = null;
			JSONObject  jsonAreaObj = null;
			List<SharedAreaVo> sharedAreaVoList = new ArrayList<SharedAreaVo>();
			List<AreaTreeVo> areaTreeVoList = new ArrayList<AreaTreeVo>();
			
			// 取得已经共享的地区信息
			JSONObject sharedAreaJson = sharedAreaService.findSharedAreaList(currAreaCode);
			if (ResultPojo.CODE_SUCCESS.equals(sharedAreaJson.getString("code")) ) {
				JSONArray  sharedAreaArray =  sharedAreaJson.getJSONArray("result");
				for (int i=0; i < sharedAreaArray.size(); i ++) {
					jsonSharedAreaObj = sharedAreaArray.getJSONObject(i);
					sharedAreaVoTmp = JSONObject.toJavaObject(jsonSharedAreaObj, SharedAreaVo.class);
					sharedAreaVoList.add(sharedAreaVoTmp);
				}
			}

			if(Contsants.AREA_LVL_ONE.equals(currAreaLvl) || Contsants.AREA_LVL_TWO.equals(currAreaLvl)) {
				AreaTreeVo  areaTreeVoTmp  = null;
				// 省级/市级
				areaVoPara.setLvl(Integer.valueOf(currAreaLvl));
				shareAreaInfo =  areaService.getAreaListByPara(areaVoPara);
				if (ResultPojo.CODE_SUCCESS.equals(shareAreaInfo.getString("code")) ) {
					JSONArray  shareAreaArray =  shareAreaInfo.getJSONArray("result");
					for (int i=0; i < shareAreaArray.size(); i ++) {
						jsonAreaObj = shareAreaArray.getJSONObject(i);
						areaTreeVoTmp = JSONObject.toJavaObject(jsonAreaObj, AreaTreeVo.class);
						if(areaTreeVoTmp.getChild() == null) {
							areaTreeVoTmp.setChild(new ArrayList<AreaTreeVo>() );
						}
						// 设置被共享的地区标示
						for(SharedAreaVo sharedAreaVo : sharedAreaVoList) {
							if(areaTreeVoTmp.getCode().equals(sharedAreaVo.getAreaCode())) {
								areaTreeVoTmp.setIsShared(Contsants.AREA_SHARED_FLAG);
								break;
							}
						}
						areaTreeVoList.add(areaTreeVoTmp);
					}
				}
				// 结果集设定
				result.setCode(ResultPojo.CODE_SUCCESS);
				result.setResult(areaTreeVoList);
				result.setMsg(ResultPojo.MSG_SUCCESS);
				return result;
			} else {
				// 县级
				AreaEntity  areaEntity = null;
				Map<String, AreaTreeVo> areaTreeNodeMap = new HashMap<String, AreaTreeVo>();
				shareAreaInfo =   areaService.getAreaListByPara(areaVoPara);
				if (ResultPojo.CODE_SUCCESS.equals(shareAreaInfo.getString("code")) ) {
					JSONArray  shareAreaArray =  shareAreaInfo.getJSONArray("result");
					for (int i=0; i < shareAreaArray.size(); i ++) {
						jsonAreaObj = shareAreaArray.getJSONObject(i);
					    areaEntity = JSONObject.toJavaObject(jsonAreaObj, AreaEntity.class);
					    if(Contsants.AREA_LVL_ONE.equals(areaEntity.getLvl()) 
					    		||  Contsants.AREA_LVL_ZERO.equals(areaEntity.getLvl()) ) {
					    	continue;
					    }
					    for(SharedAreaVo sharedAreaVo : sharedAreaVoList) {
							if(areaEntity.getCode().equals(sharedAreaVo.getAreaCode())) {
								areaEntity.setIsShared(Contsants.AREA_SHARED_FLAG);
								break;
							}
						}
					    areaTreeNodeMap.put(areaEntity.getId(),  new AreaTreeVo(areaEntity));
					}
				}
				// 组成树形结构
				for(AreaTreeVo areaTreeVo:  areaTreeNodeMap.values()) {
					String pid = areaTreeVo.getPid();
					// 增加异常数据的处理，防止死循环
					if(areaTreeVo.getId().equals(pid)) {
						continue;
					}
					if(StringUtils.isNotBlank(pid)) {
						if(areaTreeNodeMap.containsKey(pid)) {
							areaTreeNodeMap.get(pid).addChild(areaTreeVo);
						}
					}
				}
				for(AreaTreeVo areaTreeVo:  areaTreeNodeMap.values()) {
					if(Integer.valueOf(Contsants.AREA_LVL_TWO).equals(areaTreeVo.getLvl())) {
						areaTreeVoList.add(areaTreeVo);
					}
				}
				// 结果集设定
				result.setCode(ResultPojo.CODE_SUCCESS);
				result.setResult(areaTreeVoList);
				result.setMsg(ResultPojo.MSG_SUCCESS);
				return result;
			}
		}
		
		
		@ApiOperation(value = "获取已经共享地区的信息列表", httpMethod = "GET", response = OrganizationVo.class, notes = "获取已经共享地区的信息列表")
		@RequestMapping(value = "areas/list", method = RequestMethod.GET)
		public JSONObject findShareAreaList(HttpServletRequest request, HttpServletResponse response) {
			String currAreaCode = UserUtils.getCurrentUser().getAreaCode();
			//TODO 测试用
			// 县级别测试
			currAreaCode = "162401136";
			//市级别测试
			//currAreaCode = "162400000";
			return  sharedAreaService.findSharedAreaList(currAreaCode);
		}
		
		// 根据参数查询部门库
		@ApiOperation(value = "根据参数查询已共享的部门库信息", httpMethod = "POST", response = OrganizationVo.class, notes = "根据参数查询已共享的部门库信息")
		@RequestMapping(value = "areas/org/param", method = RequestMethod.POST)
		public Object findSharedOrgByParam(HttpServletRequest request, HttpServletResponse response,
				@ApiParam(value = "根据参数查询部门库", required = false) @RequestBody OrganizationVo vo) {
			ResultPojo resultInfo = new ResultPojo();
			String currAreaCode = UserUtils.getCurrentUser().getAreaCode();
			// TODO 测试用
			// 县级别测试
			//currAreaCode = "162401136";
			//市级别测试
			currAreaCode = "162400000";
			String sharedAreaCode = vo.getAreaCode();
			if(StringUtils.isBlank(sharedAreaCode)) {
				// 共享的地区为空的场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("共享地区代码不能为null或者空【 sharedAreaCode = " + vo.getAreaCode() + "】");
				resultInfo.setResult(null);
				return resultInfo;
			}
			int findFlag = 0;
			int noExpireFlag = 0;
			JSONObject jsonSharedAreaObj = null;
			SharedAreaVo sharedAreaVoTmp = null;
			// 取得已经共享的地区信息
			// 检查该共享地区的地区编码是否在共享范围内并且是否在有效期限内
			JSONObject sharedAreaJson = sharedAreaService.findSharedAreaList(currAreaCode);
			if (ResultPojo.CODE_SUCCESS.equals(sharedAreaJson.getString("code")) ) {
				JSONArray  sharedAreaArray =  sharedAreaJson.getJSONArray("result");
				for (int i=0; i < sharedAreaArray.size(); i ++) {
					jsonSharedAreaObj = sharedAreaArray.getJSONObject(i);
					sharedAreaVoTmp = JSONObject.toJavaObject(jsonSharedAreaObj, SharedAreaVo.class);
					if(sharedAreaCode.equals(sharedAreaVoTmp.getAreaCode())){
						findFlag = 1;
						long remDays = DateUtils.remDays(sharedAreaVoTmp.getEndTime());
						if(remDays >= 0) {
							noExpireFlag = 1;
						}
						break;
					}
				}
			}
			// 检查该共享地区的地区编码是否在共享范围内
			if(findFlag == 0) {
				// 共享的地区为空的场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("共享地区代码【"+sharedAreaCode +"】不在共享范围内。");
				resultInfo.setResult(null);
				return resultInfo;		
			}

			// 检查该共享地区的地区编码是否在共享范围内并且是否在有效期限内
			if(noExpireFlag == 0) {
				// 共享的地区为空的场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("共享地区代码【"+sharedAreaCode +"】的共享时间已经过期了，请重新申请。");
				resultInfo.setResult(null);
				return resultInfo;		
			}
			
			return orgService.findOrgByParam(vo);
		}
		
		// 根据参数查询部门库
		@ApiOperation(value = "根据参数查询已共享的部门库信息(APP专用)", httpMethod = "GET", response = OrganizationVo.class, notes = "根据参数查询已共享的部门库信息（APP专用）")
		@RequestMapping(value = "areas/orgTree/{sharedAreaCode}", method = RequestMethod.GET)
		public Object findSharedOrgTree(HttpServletRequest request, HttpServletResponse response,
				@ApiParam(value = "共享的地区编码", required = false) @PathVariable("sharedAreaCode") String sharedAreaCode) {
			ResultPojo resultInfo = new ResultPojo();
			String currAreaCode = UserUtils.getCurrentUser().getAreaCode();
			// TODO 测试用
			// 县级别测试
			//currAreaCode = "162401136";
			//市级别测试
			currAreaCode = "162400000";
			if(StringUtils.isBlank(sharedAreaCode)) {
				// 共享的地区为空的场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("共享地区代码不能为null或者空【 sharedAreaCode = " + sharedAreaCode + "】");
				resultInfo.setResult(null);
				return resultInfo;
			}
			int findFlag = 0;
			int noExpireFlag = 0;
			JSONObject jsonSharedAreaObj = null;
			SharedAreaVo sharedAreaVoTmp = null;
			// 取得已经共享的地区信息
			// 检查该共享地区的地区编码是否在共享范围内并且是否在有效期限内
			JSONObject sharedAreaJson = sharedAreaService.findSharedAreaList(currAreaCode);
			if (ResultPojo.CODE_SUCCESS.equals(sharedAreaJson.getString("code")) ) {
				JSONArray  sharedAreaArray =  sharedAreaJson.getJSONArray("result");
				for (int i=0; i < sharedAreaArray.size(); i ++) {
					jsonSharedAreaObj = sharedAreaArray.getJSONObject(i);
					sharedAreaVoTmp = JSONObject.toJavaObject(jsonSharedAreaObj, SharedAreaVo.class);
					if(sharedAreaCode.equals(sharedAreaVoTmp.getAreaCode())){
						findFlag = 1;
						long remDays = DateUtils.remDays(sharedAreaVoTmp.getEndTime());
						if(remDays >= 0) {
							noExpireFlag = 1;
						}
						break;
					}
				}
			}
			// 检查该共享地区的地区编码是否在共享范围内
			if(findFlag == 0) {
				// 共享的地区为空的场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("共享地区代码【"+sharedAreaCode +"】不在共享范围内。");
				resultInfo.setResult(null);
				return resultInfo;		
			}

			// 检查该共享地区的地区编码是否在共享范围内并且是否在有效期限内
			if(noExpireFlag == 0) {
				// 共享的地区为空的场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg("共享地区代码【"+sharedAreaCode +"】的共享时间已经过期了，请重新申请。");
				resultInfo.setResult(null);
				return resultInfo;		
			}
			
			return orgService.findSharedOrgTree(sharedAreaCode);
		}
}
